
<template>
  <div>
    <SearchForm
        @search="onSearch"
        @reset="onReset"
        :search-list="searchList" :search-params="searchParams">
    </SearchForm>

    <div class="table-layout">
      <el-card shadow="never">
        <div class="table-handle">
          <el-upload
              class="upload-demo"
              action=""
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleChange"
              accept=".xlsx, .xls">
            <el-button type="primary">导入Excel</el-button>
          </el-upload>
          <el-button style="margin-left: 15px" type="primary" icon="el-icon-plus" @click="onAdd">新增</el-button>
          <el-button style="margin-left: 15px" type="primary" @click="downloadTemplate">下载模板</el-button>
        </div>
        <div class="table-box">
          <el-table
              size="large"
              stripe
              border
              v-loading="loading"
              max-height="500px"
              :data="tableData"
              row-key="id"
              element-loading-spinner="el-icon-loading"
              element-loading-background="rgba(255, 255, 255, 0.8)"
              @selection-change="onSelect"
          >
            <el-table-column fixed="left" prop="major_code" label="专业编码" min-width="100px"></el-table-column>
            <el-table-column prop="school.name" label="学校" min-width="160px"></el-table-column>
            <el-table-column prop="college" label="院系" min-width="160px"></el-table-column>
            <el-table-column prop="major" label="专业名称" min-width="160px"></el-table-column>
            <el-table-column prop="major_short" label="专业简称" min-width="120px"></el-table-column>
            <el-table-column prop="length" label="学制" min-width="120px">
              <template slot-scope="scope">
                <div>{{scope.row.min_length}}~{{scope.row.max_length}}年</div>
              </template>
            </el-table-column>
            <el-table-column prop="is_part_time" label="是否接受Part-time" width="140px">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.is_part_time === 1">Y</el-tag>
                <el-tag type="info" v-else>N</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="tuition" label="学费" min-width="100px"></el-table-column>
            <el-table-column prop="apply_frequency" label="申请频次（每年）" min-width="160px"></el-table-column>
            <el-table-column prop="applyDate" label="申请时间" min-width="260px">
              <template slot-scope="scope">
                <div v-for="item in scope.row.applyDate" style="font-size: 12px;margin: 4px 0">
                  {{ item.type }}：{{ item.start_time }}~{{ item.end_time }}{{item.remark ? `【${item.remark}】` : '' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="bachelor_degree" label="本科学历" min-width="160px"></el-table-column>
            <el-table-column prop="work_experience" label="工作经验" min-width="160px"></el-table-column>
            <el-table-column prop="ielts" label="雅思" width="80px"></el-table-column>
            <el-table-column prop="toefl" label="托福" width="80px"></el-table-column>
            <el-table-column prop="us_graduate" label="美国研究生入学考试" min-width="160px"></el-table-column>
            <el-table-column prop="is_need_interview" label="是否需要面试" width="120px">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.is_need_interview === 1">Y</el-tag>
                <el-tag type="info" v-else>N</el-tag>
              </template>
            </el-table-column>

            <el-table-column prop="status" label="状态" width="100px">
              <template slot-scope="scope">
                <el-tag type="success" v-if="scope.row.status === 1">启用</el-tag>
                <el-tag type="info" v-else>禁用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="200px">
              <template slot-scope="scope">
                <el-button type="text" @click="onEdit(scope.row)">编辑专业</el-button>
                <el-button type="text" @click="onEditCourse(scope.row)">编辑课程</el-button>
                <el-button type="text" style="color: #F82222" @click="onDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>

      <div class="page-box">
        <el-pagination
            background
            :current-page="pageNo"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalSize"
            @size-change="changePageSize"
            @current-change="changePageNo"
        />
      </div>
    </div>
    <Add ref="addFormRef" @get-page="initData" />
    <el-dialog
        top="10vh"
        width="800px"
        title="专业课"
        :visible.sync="dialogValue"
        :close-on-click-modal="false"
        append-to-body
    >
      <CoursePage v-if="dialogValue" :majorId="currentDetail.id"/>
    </el-dialog>

    <el-dialog
        top="10vh"
        width="80vw"
        title="错误专业"
        :visible.sync="dialogValue2"
        :close-on-click-modal="false"
        append-to-body
    >
      <el-table
          size="large"
          stripe
          border
          v-loading="loading"
          height="500px"
          :data="errList"
          row-key="id"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(255, 255, 255, 0.8)"
          @selection-change="onSelect"
      >
        <el-table-column label="错误信息" min-width="200px" fixed="left" prop="errorMessage">
          <template slot-scope="scope">
            <el-tag type="danger">{{ scope.row.errorMessage }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-for="col in columnList" :prop="col.prop" :label="col.label" min-width="160px" show-overflow-tooltip>
         <template slot-scope="scope">
           {{ scope.row.oldData[col.prop] }}
         </template>
        </el-table-column>
      </el-table>
<!--      <template v-slot:footer>-->
<!--        <el-button type="primary" :disabled="errList.length === 0" :loading="loading" @click="onSaveErr">保存</el-button>-->
<!--        <el-button @click="dialogValue2 = false">取消</el-button>-->
<!--      </template>-->
    </el-dialog>
  </div>
</template>
<script>

import crud from "@/mixins/crud";
import { http } from "@/api";
import Add from "./add";
import CoursePage from "../course";
import * as XLSX from 'xlsx';

export default {
  name: "index",
  components: {
    Add,
    CoursePage
  },
  mixins: [crud],
  data() {
    return {
      request:http.major,
      dialogValue2: false,
      searchList: [
        {
          name: 'select',
          label: '语言',
          prop: 'lang',
          clearable: false,
          options: [
            {
              label: '中文',
              value: 'zh'
            },
            {
              label: '英文',
              value: 'en'
            }
          ]
        },
        {
          name: 'select',
          label: '学校',
          prop: 'school_id',
          clearable: true,
          options: [
          ]
        },
        {
          name: 'input',
          label: '院系',
          prop: 'college'
        },
        {
          name: 'input',
          label: '专业名称',
          prop: 'major'
        },
        {
          name: 'input',
          label: '专业简称',
          prop: 'major_short'
        },
        {
          name: 'input',
          label: '学制',
          prop: 'length'
        },
        {
          name: 'input',
          label: '学费',
          prop: 'tuition'
        },
        {
          name: 'input',
          type: 'number',
          label: '申请频次（每年）',
          prop: 'apply_frequency'
        },
        // {
        //   name: 'date',
        //   type: 'date',
        //   label: '申请时间',
        //   prop: 'applyDate'
        // },
        {
          name: 'select',
          label: '启用状态',
          prop: 'status',
          options: [
            {
              label: '启用',
              value: 1
            },
            {
              label: '禁用',
              value: 0
            }
          ]
        }
      ],
      searchParams: {
        lang: 'zh', // 默认中文lang
      },
      tableData: [

      ],
      defaultParams: {
        lang: 'zh', // 默认中文lang
      },
      columnList: [
        // 语言版本	学校	院系	领域	专业编码	专业名称	专业简称	专业介绍	学制（最短）	学制（最长）
        { prop: 'lang', label: '语言版本', map: { '中': 'zh', '英': 'en' }  },
        { prop: 'major_code', label: '专业编码' },
        { prop: 'school_name', label: '学校' },
        { prop: 'college', label: '院系' },
        { prop: 'field', label: '领域' },
        { prop: 'major', label: '专业名称' },
        { prop: 'major_short', label: '专业简称' },
        { prop: 'description', label: '专业介绍' },
        { prop: 'min_length', label: '学制（最短）' },
        { prop: 'max_length', label: '学制（最长）' },
        // 是否接受Part-time	学费	申请频次	申请时间
        { prop: 'is_part_time', label: '是否接受Part-time', map: { 'Y': 1, 'N': 0 } },
        { prop: 'tuition', label: '学费' },
        { prop: 'apply_frequency', label: '申请频次（每年）' },
        { prop: 'applyDate', label: '申请时间' },
        // 课程名称
        { prop: 'course', label: '课程名称' },
        // 本科学历	工作经验	雅思	托福	美国研究生入学考试(Graduate Record Examination)
        { prop: 'bachelor_degree', label: '本科学历' },
        { prop: 'work_experience', label: '工作经验' },
        { prop: 'ielts', label: '雅思' },
        { prop: 'toefl', label: '托福' },
        { prop: 'us_graduate', label: '美国研究生入学考试' },
        { prop: 'is_need_interview', label: '是否需要面试', map: { 'Y': 1, 'N': 0 } },
      ],
      errList: []
    }
  },
  created() {
    http.school.list().then(res => {
      this.searchList.forEach(item => {
        if (item.prop === 'school_id') {
          item.options = res.data.map(item => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      })
    })
  },
  methods: {
    handleChange(file) {
      if (!file) return;
      const reader = new FileReader();
      let tableData = []
      reader.onload = (e) => {
        try {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: 'array' });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

          if (jsonData.length > 0) {
            tableData = jsonData.slice(1).map(row => {
              const rowData = {
                oldData: {
                }
              };
              this.columnList.forEach((field, index) => {
                rowData.oldData[field.prop] = row[index];
                if (field.map) {
                  rowData[field.prop] = field.map[row[index]]
                } else {
                  rowData[field.prop] = row[index];
                }
                // 特殊处理时间
                if (field.prop === 'applyDate') {
                  this.handleApplyDate(rowData, field.prop, row[index])
                }
                if (field.prop === 'course') {
                  this.handleCourse(rowData, field.prop, row[index])
                }
              });
              return rowData;
            });
          }
          this.uploadDataList(tableData)
        } catch (error) {
          console.error('Excel解析错误:', error);
          this.$message.error('Excel文件解析失败');
        }
      };

      reader.readAsArrayBuffer(file.raw);
    },
    handleApplyDate(rowData, prop, value) {
        // 早鸟/11-24/03-24/这是一条备注,早鸟/11-24/03-24/这是一条备注,
      let list = value.split(',')
      let applyDate = list.map(item => {
        let _list = item.split('/')
        return {
          type: _list[0] || '',
          start_time: _list[1] || '',
          end_time: _list[2] || '',
          remark: _list[3] || ''
        }
      })
      rowData[prop] = applyDate
    },
    handleCourse(rowData, prop, value) {
      // 必修课程/01/课程名称,必修课程/01/课程名称,必修课程/01/课程名称,
      let list = value.split(',')
      let courseList = list.map(item => {
        let _list = item.split('/')
        return {
          type: _list[0] || '',
          code: _list[1] || '',
          name: _list[2] || '',
        }
      })
      rowData[prop] = courseList
    },
    uploadDataList(tableData) {
      this.loading = true
      http.major.createList(tableData).then(res => {
        if (res.data.errList.length) {
          this.$message.error(`导入成功${res.data.successList.length}条，失败${res.data.errList.length}条`);
          setTimeout(() => {
            this.dialogValue2 = true
            this.errList = res.data.errList
          },300)
        } else {
          console.log('res,this.onSearch')
          this.$message.success('导入成功');
          setTimeout(() => {
            this.onSearch()
          },300)
        }
      }).finally(err => {
        this.loading = false
      }).catch(e => {
        console.log(e)
      })
    },
    onSaveErr() {
      let tableData = this.errList.map(_row => {
        let row = {
          ..._row.oldData,
        }
        const rowData = {
          oldData: {
          }
        };
        this.columnList.forEach((field, index) => {
          rowData.oldData[field.prop] = row[index];
          if (field.map) {
            rowData[field.prop] = field.map[row[index]]
          } else {
            rowData[field.prop] = row[index];
          }
          // 特殊处理时间
          if (field.prop === 'applyDate') {
            this.handleApplyDate(rowData, field.prop, row[index])
          }
          if (field.prop === 'course') {
            this.handleCourse(rowData, field.prop, row[index])
          }
        });
        return rowData;
      });
      this.uploadDataList(tableData)
    },
    onEditCourse(row) {
      this.currentDetail = {
        ...row
      }
      this.dialogValue = true
    },
    downloadTemplate() {
      // vue下载public中的模版 专业信息导入模版.xlsx
      let url = '专业信息导入模板.xlsx'
      const link = document.createElement('a');
      link.href = url;
      link.download = '专业信息导入模板.xlsx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    }
  }
}
</script>

<style scoped lang="scss">

</style>
